<?php

namespace App\Console\Commands;

use App\Library\Lock;
use App\Library\Logic\WithdrawLogic;
use App\Library\Service\Payment\AlipayService;
use App\Library\Service\Payment\WechatService;
use App\Library\YsdLib;
use Exception;
use Illuminate\Console\Command;
use Yansongda\Artful\Exception\ContainerException;
use Yansongda\Artful\Exception\InvalidParamsException;
use Yansongda\Artful\Exception\ServiceNotFoundException;
use Yansongda\Pay\Pay;

class WithdrawCommand extends Command
{
    /**
     * 手动提现
     *
     * @var string
     */
    protected $signature = 'command:withdraw {serialNumber}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     * @return void
     * @throws Exception
     */
    public function handle(): void
    {
        $serialNumber = $this->argument('serialNumber');
        if (empty($serialNumber) || strlen($serialNumber) !== 20) return;
        Lock::get($serialNumber . $this->signature, function () use ($serialNumber) {
            $this->handleLock($serialNumber);
        });
    }

    /**
     * @throws ServiceNotFoundException
     * @throws ContainerException
     * @throws InvalidParamsException
     */
    private function handleLock(string $serialNumber): void
    {
        $withdraw = WithdrawLogic::findBySerialNumber($serialNumber);
        if (is_null($withdraw)) return;
        else if ($withdraw->status !== 1 || is_null($withdraw->audit_at)) return;
        else if ($withdraw->status_arrival !== 0 || !is_null($withdraw->file_id)) return;
        else if (!is_null($withdraw->pay_at) || !is_null($withdraw->result) || !is_null($withdraw->find)) return;
        if ($withdraw->payment_method_id === 1) {
            Pay::config(YsdLib::config('alipay'));
            if (prod()) AlipayService::withdraw($withdraw);
            else AlipayService::withdrawTest($withdraw);
        }
        if ($withdraw->payment_method_id === 2) {
            Pay::config(YsdLib::config());
            if (prod()) WechatService::withdraw($withdraw);
            else WechatService::withdrawTest($withdraw);
        }
    }
}
